//
//  HHYUtils.m
//  Shop
//
//  Created by apple on 2019/3/7.
//  Copyright © 2019 apple. All rights reserved.
//

#import "HHYUtils.h"

#import "HHYHeader.h"

@implementation HHYUtils
+ (NSString *)getCurrentTimeWithNum:(float)num {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    //    [formatter setTimeZone:timeZone];
    //现在时间,你可以输出来看下是什么格式
    NSDate *datenow = [NSDate dateWithTimeIntervalSince1970:num];
    //----------将nsdate按formatter格式转成nsstring
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    return currentTimeString;
}


#pragma mark - view切圆角
+ (void)setupCornerToView:(UIView *)view rectCenter:(UIRectCorner)rectCenter radius:(CGFloat)radius backgroundColor:(UIColor *)bgColor {
    //把 view 的 左下角 和 右下角的直角切成圆角
    view.backgroundColor = bgColor;
    
    //设置切哪个直角
    //    UIRectCornerTopLeft     = 1 << 0,  左上角
    //    UIRectCornerTopRight    = 1 << 1,  右上角
    //    UIRectCornerBottomLeft  = 1 << 2,  左下角
    //    UIRectCornerBottomRight = 1 << 3,  右下角
    //    UIRectCornerAllCorners  = ~0UL     全部角
    //得到view的遮罩路径
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:rectCenter cornerRadii:CGSizeMake(radius,radius)];
    //创建 layer
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    //赋值
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

+ (UIWindow *)mainWindow
{
    UIApplication *app = [UIApplication sharedApplication];
    if ([app.delegate respondsToSelector:@selector(window)])
    {
        if (@available(iOS 11.0, *)) {
            // iOS 11.0 及以后的版本
            return [app.delegate window];
        } else {
            // iOS 11.0 之前
        }
        return [app keyWindow];
    }
    else
    {
        return [app keyWindow];
    }
}

#pragma mark - 计算文字宽度
+ (CGSize)calculateStr:(NSString *)string font:(UIFont *)font viewSize:(CGSize)viewSize {
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, viewSize.width, viewSize.height)];
    
    textView.text = string;
    
    textView.font = font;
    
    CGSize constraint = [textView sizeThatFits:viewSize];
    return constraint;

//    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
//    NSDictionary * attributes = @{
//                                  NSFontAttributeName:font,
//                                  NSParagraphStyleAttributeName: paragraphStyle
//                                  };
//    CGRect rect = [string boundingRectWithSize:viewSize
//                                           options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
//                                        attributes:attributes
//                                           context:nil];
//    return rect.size;
}

#pragma mark - 字典转JSON
+ (NSString *)convertToJsonData:(NSDictionary *)dict

{
    //解决NULL问题
    for (id value in dict.allKeys) {
        if (![value isKindOfClass:[NSString class]]) {
            return nil;
        }
    }
    
    if (!dict) {
        return nil;
    }
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
}

//判断是否全是空格
+ (BOOL) isEmpty:(NSString *) str {
    if (!str) {
        
        return true;
        
    } else {
        
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            
            return true;
            
        } else {
            
            return false;
            
        }
        
    }
    
}

//#pragma mark - 网络监听
//+ (void)isConnectionAvailableWithAvaliable:(handler)avaliable unAvaliable:(handler)unAvaliable {
//    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        switch (status) {
//            case AFNetworkReachabilityStatusUnknown:
//                
//                break;
//            case AFNetworkReachabilityStatusNotReachable:{
//                unAvaliable();
//            }
//                break;
//            case AFNetworkReachabilityStatusReachableViaWiFi:{
//                avaliable();
//            }
//                break;
//            case AFNetworkReachabilityStatusReachableViaWWAN:{
//                avaliable();
//            }
//                break;
//            default:
//                break;
//        }
//    }];
//    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
//}
//
#pragma mark - 提示文本
+ (void)textExampleLong:(NSString *)text {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIView *keyWindow = [HHYUtils mainWindow];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
        // Set the text mode to show only text.
        hud.mode = MBProgressHUDModeText;
        hud.labelText = text;
        hud.label.numberOfLines = 0;
        // Move to bottm center.
        [hud hide:YES afterDelay:1.5f];
    });
}

+(BOOL)isChina
{
    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    
    [NSTimeZone resetSystemTimeZone]; // 重置手机系统的时区
    
    NSInteger dayOffset = [NSTimeZone localTimeZone].secondsFromGMT;
    
    dayOffset = dayOffset/3600;
    
    NSString *tzStr = [NSString stringWithFormat:@"%ld", (long)dayOffset];
    
    
    NSTimeZone * cTimeZone = [NSTimeZone systemTimeZone];
    
    
    if ([currentLanguage containsString:@"zh-Han"]) {
        
        if ([tzStr isEqualToString:@"8"] || [cTimeZone.name isEqualToString:@"Asia/Urumqi"] || [cTimeZone.name isEqualToString:@"Asia/Kashgar"] ) {
            
            return YES;
            
        }else
        {
            return NO;
        }
        
    }else
    {
        return NO;
    }
}

#pragma mark - 弹出框
+ (void)showAlertWithTitle:(NSString *)title message:(NSString *)message cancleTitle:(NSString *)cancleTitle cancleBlock:(myCallback)cancleCllback doneTitle:(NSString *)doneTitle doneBlock:(myCallback)doneCallback controller:(UIViewController *)vc {
    //UIAlertController风格：UIAlertControllerStyleAlert
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
                                                                             message:message
                                                                      preferredStyle:UIAlertControllerStyleAlert ];
    if (cancleTitle) {
        __block myCallback cancle = cancleCllback;
        //添加取消到UIAlertController中
        UIAlertAction *cancelAction;
        if (cancle) {
            cancelAction = [UIAlertAction actionWithTitle:cancleTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                cancle(@"Cancle");
            }];
        } else {
            cancelAction = [UIAlertAction actionWithTitle:cancleTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
        }
        [alertController addAction:cancelAction];
    }
    if (doneTitle) {
        __block myCallback done = doneCallback;
        UIAlertAction *OKAction;
        if (done) {
            //添加确定到UIAlertController中
            OKAction = [UIAlertAction actionWithTitle:doneTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                done(@"Done");
            }];
        } else {
            OKAction = [UIAlertAction actionWithTitle:doneTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
        }
        [alertController addAction:OKAction];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [vc presentViewController:alertController animated:YES completion:nil];
    });
}

@end
